package com.yzj.musicplayer.Player;

import com.yzj.musicplayer.util.Log;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.global.resource.BaseFileDescriptor;
import ohos.global.resource.RawFileEntry;
import ohos.media.player.Player;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/*自定义的播放器类*/
public class PlayerManager {
    private static final String TAG = "=>" + PlayerManager.class.getSimpleName();
    /* 把播放状态设置为“事件” */
    private static final int PLAY = 0x0000001;

    private static final int PAUSE = 0x0000002;

    private static final int FINISH = 0x0000003;

    private static final int PROGRESS = 0x0000004;

    private static final int DELAY_TIME = 1000;

    private static final int PERIOD = 1000;
    /* 把播放状态设置为“事件” */

    /* 定义一个播放器对象 */
    private Player mPlayer;
    /* 上下文对象 */
    private Context context;
    /* 当前歌曲路径 */
    private String currentUri;
    /* 计时器任务对象 */
    private TimerTask timerTask;
    /* 计时器对象 */
    private Timer timer;

    private boolean isPrepared;
    /* 播放状态监听对象 */
    private StateListener stateListener;
    /* 事件处理对象 */
    private final EventHandler handler = new EventHandler(EventRunner.current()) {
        @Override
        protected void processEvent(InnerEvent event) {
            switch (event.eventId) {
                case PLAY: {
                    Log.debug(TAG, "processEvent PLAY_STATE_PLAY");
                    stateListener.onPlaySuccess(getTotalTime());
                    break;
                }
                case PAUSE: {
                    stateListener.onPauseSuccess();
                    break;
                }
                case FINISH: {
                    Log.debug(TAG, "processEvent PLAY_STATE_FINISH");
                    stateListener.onMusicFinished();
                    break;
                }
                case PROGRESS: {
                    stateListener.onPositionChange(mPlayer.getCurrentTime());
                    break;
                }
                default:
                    break;
            }
        }
    };

    public PlayerManager(Context context, String currentUri) {
        this.context = context;
        this.currentUri = currentUri;
    }

    /**
     *  首先播放之前要准备好媒体资源
     */
    public void prepareMusic(){
        Log.info(TAG, "init,currentUri:  " + currentUri);
        mPlayer = new Player(context);
        mPlayer.setPlayerCallback(new PlayCallBack());
        setResource(currentUri);
    }

    /**
     *  准备好音频路径 准备媒体资源
     * @param Uri
     */
    public void setResource(String Uri) {
        try {
            RawFileEntry rawFileEntry = context.getResourceManager().getRawFileEntry(Uri);
            BaseFileDescriptor baseFileDescriptor = rawFileEntry.openRawFileDescriptor();
            //LogUtil.info(TAG, "setResource,baseFileDescriptor :  " + baseFileDescriptor);
            if (!mPlayer.setSource(baseFileDescriptor)) {
                Log.info(TAG, "该路径无效！");
                return;
            }
            //准备播放环境并缓冲媒体数据。
            isPrepared = mPlayer.prepare();
            Log.info(TAG, "播放是否准备就绪:  " + isPrepared);
            //歌曲名称
            String listenerUri = currentUri.substring(currentUri.lastIndexOf("/") + 1, currentUri.lastIndexOf("."));
            stateListener.onUriSet(listenerUri);
            Log.info(TAG, "当前监听的歌曲路径:  " + listenerUri);
        } catch (IOException e) {
            Log.error(TAG, "io exception");
        }
    }

    /**
     *  播放
     */
    public void play() {
        try {
            if (!isPrepared) {
                Log.error(TAG, "资源准备失败");
                return;
            }
            //如果开始播放则返回真； 否则返回 false。
            if (!mPlayer.play()) {
                Log.error(TAG, "播放失败");
                return;
            }
            startTimetask();
            handler.sendEvent(PLAY);
        } catch (IllegalArgumentException e) {
            Log.error(TAG, e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 暂停
     */
    public void pause() {
        if (!mPlayer.pause()) {
            Log.info(TAG, "暂停失败");
            return;
        }
        //停止计时
        finishTimetask();
        //
        handler.sendEvent(PAUSE);
    }

    /**
     * 定时事件通知更新进度条
     * DELAY_TIME 延迟1s
     * PERIOD 两个事件间隔1s
     */
    private void startTimetask() {
        Log.debug(TAG, "startTask");
        finishTimetask();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                handler.sendEvent(PROGRESS);
            }
        };
        timer = new Timer();
        timer.schedule(timerTask, DELAY_TIME, PERIOD);
    }

    /*
     *  结束计时器任务
     * */
    private void finishTimetask() {
        Log.debug(TAG, "停止计时");
        if (timer != null && timerTask != null) {
            timer.cancel();
            timer = null;
            timerTask = null;
        }
    }

    /**
     *  获取歌曲的总时间
     * @return
     */
    public int getTotalTime() {
        Log.debug(TAG, "getTotalTime:" + mPlayer.getDuration());
        return mPlayer.getDuration();
    }

    /**
     *  切换歌曲
     * @param uri
     */
    public void switchMusic(String uri) {
        currentUri = uri;
        //设置资源
        setResource(currentUri);
        //播放
        play();
    }

    /**
     *   更新播放进度
     * @param currentTime
     */

    public void rewindTo(int currentTime) {
        mPlayer.rewindTo(currentTime * 1000);
    }

    /**
     * 释放播放器资源
     */
    public void releasePlayer() {
        if (mPlayer == null) {
            return;
        }
        mPlayer.stop();
        mPlayer.release();
    }

    public boolean isPlaying() {

        return mPlayer.isNowPlaying();
    }

    public void setPlayerStateListener(StateListener stateListener) {
        this.stateListener = stateListener;
    }

    class PlayCallBack implements Player.IPlayerCallback {
        String TAG;

        public PlayCallBack() {
        }
        public PlayCallBack(String s){
            TAG = s;
        }
        /**
         * 当媒体文件准备好播放时调用。
         */
        @Override
        public void onPrepared() {
            Log.info(TAG, "媒体资源准备就绪");
        }
        /**
         * 当收到播放器消息或警报时调用。
         *
         * @param type
         * @param extra
         */
        @Override
        public void onMessage(int type, int extra) {
            Log.info(TAG, "onMessage  " + type + "-" + extra);

        }
        /**
         * 收到播放器错误消息时调用。
         *
         * @param errorType
         * @param errorCode
         */
        @Override
        public void onError(int errorType, int errorCode) {
            Log.info(TAG, "播放器出错  " + errorType + "-" + errorCode);
        }
        /**
         * 当视频大小改变时调用。
         *
         * @param width
         * @param height
         */
        @Override
        public void onResolutionChanged(int width, int height) {
            Log.info(TAG, "视频大小发生改变  " + width + "-" + height);
        }
        /**
         * 播放完成时调用。
         */
        @Override
        public void onPlayBackComplete() {

            Log.info(TAG, "onPlayBackComplete----------------");
            handler.sendEvent(FINISH);
        }
        /**
         * 当播放位置被 Player.rewindTo(long) 改变时调用。
         */
        @Override
        public void onRewindToComplete() {
            Log.info(TAG, "播放位置已更新");
        }

        @Override
        public void onBufferingChange(int i) {

        }

        @Override
        public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {

        }

        @Override
        public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {

        }
    }


}
